import { _decorator, Component, Label, tween, Vec3, director } from 'cc';
import { GameManager } from '../core/GameManager';

const { ccclass, property } = _decorator;

/**
 * 分数显示组件
 * 负责显示和更新游戏分数
 */
@ccclass('ScoreDisplay')
export class ScoreDisplay extends Component {
    @property(Label)
    private scoreLabel: Label = null;
    
    @property(Label)
    private highScoreLabel: Label = null;
    
    @property({type: String, tooltip: "分数前缀文本"})
    private scorePrefix: string = "分数: ";
    
    @property({type: String, tooltip: "最高分前缀文本"})
    private highScorePrefix: string = "最高分: ";
    
    private _currentScore: number = 0;
    private _displayScore: number = 0;
    private _highScore: number = 0;

    @property(GameManager)
    private gameManager: GameManager = null;

    // 声明scoreAnimationStep属性
    private scoreAnimationStep: Function = null;
    
    // 生命周期函数
    onLoad() {
        if (!this.scoreLabel) {
            this.scoreLabel = this.getComponent(Label);
        }
        
        // 从本地存储加载最高分
        this.loadHighScore();
    }
    
    start() {
        // 初始化显示
        this.updateScoreDisplay();
        this.updateHighScoreDisplay();
        
        // 监听分数变化
        this.schedule(this.checkScore, 0.1);
        console.log("开始监听分数变化");
    }
    
    onDestroy() {
        // 取消所有计时器
        this.unscheduleAllCallbacks();
        if (this.scoreAnimationStep) {
            this.unschedule(this.scoreAnimationStep);
        }
    }
    
    /**
     * 检查分数是否变化
     */
    private checkScore(): void {
        // 直接从场景中查找GameManager，确保使用最新实例
        const gameManager = this.gameManager;
        if (gameManager) {
            const newScore = gameManager.score;
            console.log("检查到GameManager分数:", newScore, "当前显示分数:", this._currentScore);
            
            if (newScore !== this._currentScore) {
                this.updateScore(newScore);
            }
        } else {
            console.warn("未找到GameManager组件");
        }
    }
    
    /**
     * 更新分数
     */
    private updateScore(newScore: number): void {
        console.log("更新分数:", newScore);
        // 记录当前分数
        this._currentScore = newScore;
        
        // 动画显示分数变化
        this.animateScoreChange(this._displayScore, newScore);
        
        // 检查是否为新的最高分
        if (newScore > this._highScore) {
            this._highScore = newScore;
            this.updateHighScoreDisplay();
            this.saveHighScore();
        }
    }
    
    /**
     * 更新分数显示
     */
    private updateScoreDisplay(): void {
        if (this.scoreLabel) {
            this.scoreLabel.string = this.scorePrefix + this._displayScore;
        }
    }
    
    /**
     * 更新最高分显示
     */
    private updateHighScoreDisplay(): void {
        if (this.highScoreLabel) {
            this.highScoreLabel.string = this.highScorePrefix + this._highScore;
        }
    }
    
    /**
     * 分数变化动画
     */
    private animateScoreChange(fromScore: number, toScore: number): void {
        // 取消之前的动画
        if (this.scoreAnimationStep) {
            this.unschedule(this.scoreAnimationStep);
        }
        
        // 设置动画参数
        const duration = 0.5; // 动画持续时间
        const steps = 10; // 动画步数
        const stepDuration = duration / steps; // 每步持续时间
        const scoreStep = (toScore - fromScore) / steps; // 每步分数增量
        
        let currentStep = 0;
        
        // 执行动画
        const scoreAnimationStep = () => {
            currentStep++;
            this._displayScore = Math.floor(fromScore + scoreStep * currentStep);
            this.updateScoreDisplay();
            
            // 添加缩放动画效果
            if (this.scoreLabel && this.scoreLabel.node) {
                tween(this.scoreLabel.node)
                    .to(0.05, { scale: new Vec3(1.2, 1.2, 1) })
                    .to(0.05, { scale: new Vec3(1.0, 1.0, 1) })
                    .start();
            }
            
            // 动画结束
            if (currentStep >= steps) {
                this.unschedule(scoreAnimationStep);
                this._displayScore = toScore;
                this.updateScoreDisplay();
            }
        };
        
        this.scoreAnimationStep = scoreAnimationStep;
        this.schedule(scoreAnimationStep, stepDuration, steps - 1);
        
        // 如果没有动画步骤，直接更新
        if (steps <= 1) {
            this._displayScore = toScore;
            this.updateScoreDisplay();
        }
    }
    
    /**
     * 保存最高分到本地存储
     */
    private saveHighScore(): void {
        try {
            localStorage.setItem('match3_highscore', this._highScore.toString());
        } catch (e) {
            console.error("保存最高分失败:", e);
        }
    }
    
    /**
     * 从本地存储加载最高分
     */
    private loadHighScore(): void {
        try {
            const savedScore = localStorage.getItem('match3_highscore');
            if (savedScore) {
                this._highScore = parseInt(savedScore);
            }
        } catch (e) {
            console.error("加载最高分失败:", e);
        }
    }
    
    /**
     * 强制更新分数显示
     */
    public forceUpdateScore(score: number): void {
        console.log("强制更新分数为:", score);
        this._currentScore = score;
        this._displayScore = score;
        this.updateScoreDisplay();
    }
    
    /**
     * 重置分数
     */
    public resetScore(): void {
        console.log("重置分数显示");
        
        // 取消所有正在进行的动画
        if (this.scoreAnimationStep) {
            this.unschedule(this.scoreAnimationStep);
            this.scoreAnimationStep = null;
        }
        
        // 设置分数为0
        this._currentScore = 0;
        this._displayScore = 0;
        
        // 更新显示
        this.updateScoreDisplay();
        
        // 重新开始监听
        this.unschedule(this.checkScore);
        this.schedule(this.checkScore, 0.1);
        
        console.log("分数已重置为:", this._displayScore);
    }
    
    /**
     * 获取当前分数
     */
    public get currentScore(): number {
        return this._currentScore;
    }
} 